package com.findtech.threePomelos.fragment;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.findtech.threePomelos.base.MyApplication;
import com.findtech.threePomelos.R;
import com.findtech.threePomelos.bluetooth.AppManager;
import com.findtech.threePomelos.bluetooth.BAdapter;
import com.findtech.threePomelos.utils.ToastUtil;

import java.util.ArrayList;

public class SearchFragment extends Fragment implements
        OnItemClickListener, AppManager.RFStarManageListener {
    private ListView list = null;
    private BAdapter bleAdapter = null;
    private ArrayList<BluetoothDevice> arraySource = null;
    private MyApplication app = null;
    private Context mContext;
    SelectBlueDevice mSelectBlueDevice;
    final private int REQUEST_CODE_ASK_ACCESS_COARSE_LOCATION_PERMISSIONS = 123;
    final private int REQUEST_CODE_ASK_ACCESS_FINE_LOCATION_PERMISSIONS = 124;

    public interface SelectBlueDevice {
        void selectBlueDevice(ArrayList<BluetoothDevice> arraySource, int position);
    }

    public void setSelectBlueDeviceListener(SelectBlueDevice selectBlueDevice) {
        mSelectBlueDevice = selectBlueDevice;
    }

    public SearchFragment() {
    }

    public SearchFragment(Context context) {
        mContext = context;
        Log.d("ZZ", "SearchFragment");
    }

    @SuppressWarnings("static-access")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Log.d(MyApplication.TAG, "onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(MyApplication.TAG, "onCreateView");
        View view = inflater.inflate(R.layout.activity_search, container, false);
        this.initView(view);
        app = (MyApplication) mContext.getApplicationContext();
        if (app.manager.cubicBLEDevice != null) {
            try {
                app.manager.cubicBLEDevice.disconnectedDevice();
            } catch (Exception e) {
                Log.d("ZZ", "SearchFragment disconnectedDevice e = " + e);
            }
            app.manager.cubicBLEDevice = null;
        }

        return view;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        app.manager.setRFstarBLEManagerListener(this);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            app.manager.startScanBluetoothDevice();
        } else {
            startScanBluetoothDevice();
        }
        app.manager.isEnabled((Activity) mContext);
        Log.d(MyApplication.TAG, "onResume");
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void startScanBluetoothDevice() {
        int hasAccessCoarseLocationPermission = mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        int hasAccessFineLocationPermission = mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);

        if (hasAccessCoarseLocationPermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE_ASK_ACCESS_COARSE_LOCATION_PERMISSIONS);
            return;
        }
        if (hasAccessFineLocationPermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE_ASK_ACCESS_FINE_LOCATION_PERMISSIONS);
            return;
        }

        app.manager.startScanBluetoothDevice();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        arraySource.clear();
        bleAdapter.notifyDataSetChanged();
        app.manager.stopScanBluetoothDevice();
    }

    protected void initView(View view) {
        list = (ListView) view.findViewById(R.id.list);
        list.setOnItemClickListener(this);
        arraySource = new ArrayList<>();
        try {
            bleAdapter = new BAdapter(mContext, arraySource);
        } catch (Exception e) {
            e.printStackTrace();
        }
        list.setAdapter(bleAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        super.onActivityResult(requestCode, resultCode, data);
        app.manager.onRequestResult(requestCode, resultCode, data);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        mSelectBlueDevice.selectBlueDevice(arraySource, arg2);
    }

    /**
     * 扫描到的蓝牙设备
     */
    @Override
    public void RFstarBLEManageListener(BluetoothDevice device, int rssi,
                                        byte[] scanRecord) {
        // TODO Auto-generated method stub
        Log.d(MyApplication.TAG, "scanrecord : " + device.getAddress());// device.getName());
        arraySource.add(device);
        bleAdapter.notifyDataSetChanged();
    }

    @Override
    public void RFstopBLEManageListener(BluetoothDevice device, int rssi, byte[] scanRecord) {

    }

    @Override
    public void RFstarBLEManageStartScan() {
        // TODO Auto-generated method stub
        // showMessage("开始扫描设备");
        this.arraySource.clear();
    }

    @Override
    public void RFstarBLEManageStopScan() {
        // TODO Auto-generated method stub
        // showMessage("扫描设备结束");
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_ACCESS_COARSE_LOCATION_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    app.manager.startScanBluetoothDevice();
                } else {
                    // Permission Denied
                    ToastUtil.showToast(mContext, "取消授权将无法搜索婴儿推车");
                }
                break;
            case REQUEST_CODE_ASK_ACCESS_FINE_LOCATION_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    app.manager.startScanBluetoothDevice();
                } else {
                    // Permission Denied
                    ToastUtil.showToast(mContext, "取消授权将无法搜索婴儿推车");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
